﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NLog;

namespace OpenDoPE_Wed
{
    /// <summary>
    /// The GlobalErrorHandler class ensures
    /// that we have hooked all necessary
    /// events to capture unhandled exceptions in our appdomains.
    /// See http://winterdom.com/2006/08/exceptionhandlingvstooutlookandothertopics
    /// </summary>
    static class GlobalErrorHandler
    {

        static Logger log = LogManager.GetLogger("OpenDoPE_Wed");

        /// <summary>
        /// Catch unhandled exceptions.  This doesn't include errors in our background worker.
        /// See formProgress.bw_RunWorkerCompleted regarding those. There is generally
        /// no point putting try/catch in ribbon stuff, since that won't even catch
        /// errors which occur in forms (nor errors which occur in our background worker)
        /// 
        /// Note that we can only catch unhandled exceptions when debugging if we have
        /// [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        /// 
        /// </summary>
        public static void Ensure()
                {
                    // hook WinForms
                    Application.ThreadException += OnApplicationUnhandledException;

                    AppDomain.CurrentDomain.UnhandledException += OnDomainUnhandledException;
                }

                private static void OnApplicationUnhandledException(object sender, 
                    System.Threading.ThreadExceptionEventArgs e)
                {
                    HandleException(e.Exception);
                }

                private static void OnDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
                {
                    HandleException((Exception)e.ExceptionObject);
                }

        public static string HandleException(Exception exp)
        {
            return HandleException(exp, true);//, false);
        }

        //public static string HandleException(Exception exp, bool showMessage)
        //{
        //    return HandleException(exp, showMessage, false);
        //}

        public static string HandleException(Exception exp, bool showMessage)//, bool bwWorker)
        {
            //log.Error("Exception type:" + exp.GetType().FullName);
            //log.Error("Exception message:" + exp.Message);
            log.Error( exp );

            if (exp.InnerException != null)
            {
                log.Error("Inner exception:" + exp.InnerException.ToString() );
                //log.Error("Inner exception message:" + exp.InnerException.Message);
            }

            String customMessage = exp.Message;

            // display the error information to the user as well as to allow him/her to send an email-report of the error for diagnostics.


                    showMessage = true;
            // TODO set on a case by case basis (pass in?)
                    customMessage = "Plutext AMP License missing/expired.  Please contact your admin.";
            
            if (exp is System.Runtime.InteropServices.COMException)
            {
                System.Runtime.InteropServices.COMException comEx = (System.Runtime.InteropServices.COMException)exp;
                log.Error("HRESULT: " + comEx.ErrorCode);
            }

            //if (showMessage && !bwWorker)  // no need if background worker, and in fact, can't
            //{
            //    MessageBox.Show(customMessage);
            //}
            log.Error(exp.Message, exp);

            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                log.Error("Displaying form...");
                try
                {
                    //FormErrorReport form = new FormErrorReport(exp);
                    //form.ShowDialog();
                }
                catch (Exception e)
                {
                    log.Error("Can't display error form?!?");
                    log.Error(e);
                    System.Windows.Forms.MessageBox.Show("An error occurred in Word. You'll need to restart it in order to continue using Results Springboard.");
                }
            }
            else
            {
                System.Windows.Forms.MessageBox.Show(exp.Message);
                log.Error("No network available");
            }

            return customMessage;

        }

    } // class GlobalErrorHandler}

}
